package com.hwadee.teachingprocessmanagementsystem.service.base.impl;

import com.hwadee.teachingprocessmanagementsystem.dao.TableDao;
import com.hwadee.teachingprocessmanagementsystem.dto.TableDto;
import com.hwadee.teachingprocessmanagementsystem.service.base.TableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 数据库表服务实现类
 * @Author: Jukomu
 * @Package: com.hwadee.teachingprocessmanagementsystem.service.base.impl
 * @Project: TeachingProcessManagementSystem
 * @name: TableServiceImpl
 * @Date: 2024/7/17-23:34
 * @Filename: TableServiceImpl
 */
@Service("tableService")
public class TableServiceImpl<T> implements TableService<T> {
    @Autowired
    private TableDao tableDao;
    /**
     * 获取所有表
     * @return
     */
    @Override
    public List<String> getAllTables() {
        return this.tableDao.getAllTable();
    }

    @Override
    public <T> List<T> getTableDetail(String tableName, Class<T> type) throws Exception {
        List<Map<String, Object>> results = this.tableDao.getTableDetail(tableName);

        List<T> typedResults = new ArrayList<>();
        for (Map<String, Object> result : results) {
            T instance = type.getDeclaredConstructor().newInstance();
            for (Field field : type.getDeclaredFields()) {
                field.setAccessible(true);
                if (java.lang.reflect.Modifier.isStatic(field.getModifiers()) || java.lang.reflect.Modifier.isFinal(field.getModifiers())) {
                    continue; // Skip static and final fields
                }
                field.set(instance, result.get(camelToSnakeCase(field.getName())));
            }
            typedResults.add(instance);
        }
        return typedResults;
    }

    @Override
    public int updateTable(String tableName, T entity) {
        return this.tableDao.updateTable(tableName, entity);
    }

    @Override
    public int deleteTable(String tableName, T entity) {
        return this.tableDao.deleteTable(tableName, entity);
    }

    @Override
    public int createTable(String tableName, T entity) {
        return this.tableDao.createTable(tableName, entity);
    }

    public static String camelToSnakeCase(String camelCase) {
        if (camelCase == null || camelCase.isEmpty()) {
            return camelCase;
        }

        StringBuilder snakeCase = new StringBuilder();
        char[] charArray = camelCase.toCharArray();

        for (char c : charArray) {
            if (Character.isUpperCase(c)) {
                if (snakeCase.length() > 0) {
                    snakeCase.append('_');
                }
                snakeCase.append(Character.toLowerCase(c));
            } else {
                snakeCase.append(c);
            }
        }

        return snakeCase.toString();
    }
}
